using NodeCanvas.Variables;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("Repeat")]
	[Category("Decorators")]
	[Description("Repeat the child either x times or until it returns the specified status, or forever")]
	[Icon("Repeat")]
	public class BTRepeater : BTDecorator
	{
		public enum RepeatTypes
		{
			RepeatTimes = 0,
			RepeatUntil = 1,
			RepeatForever = 2
		}

		public enum RepeatUntil
		{
			Failure = 0,
			Success = 1
		}

		public RepeatTypes repeatType;

		public RepeatUntil repeatUntil = RepeatUntil.Success;

		public BBInt repeatTimes = new BBInt
		{
			value = 1
		};

		private int currentIteration = 1;

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			if (!base.decoratedConnection)
			{
				return Status.Resting;
			}
			base.status = base.decoratedConnection.Execute(agent, blackboard);
			if (base.status == Status.Resting)
			{
				return Status.Running;
			}
			if (base.status != Status.Running)
			{
				if (repeatType == RepeatTypes.RepeatTimes)
				{
					repeatTimes.value = Mathf.Max(repeatTimes.value, 1);
					if (currentIteration >= repeatTimes.value)
					{
						return base.status;
					}
					currentIteration++;
				}
				else if (repeatType == RepeatTypes.RepeatUntil && base.status == (Status)repeatUntil)
				{
					return base.status;
				}
				base.decoratedConnection.ResetConnection();
				return Status.Running;
			}
			return base.status;
		}

		protected override void OnReset()
		{
			currentIteration = 1;
		}
	}
}
